//
//  CEIViewController.m
//  Balance
//
//  Created by Calvin Kuo on 12-05-09.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

/*
 Status: changed
 Last Merge Date: 05-30-2012
 Last Change Date: 
 Changes:
 1. country plot data
 */

#import "CEIViewController.h"
#import "CEIData.h"
#import "ColorUtility.h"
#import "CustomerDetailTableViewController.h"

@implementation CEIViewController

@synthesize detailItem = _detailItem;
@synthesize pageControl;
@synthesize scrollView;
@synthesize lineHostingView = _lineHostingView;
@synthesize sliderHostingView = _sliderHostingView;
@synthesize priorButton = _priorButton;
@synthesize allCollectorsButton = _allCollectorsButton;
@synthesize barHostingView = _barHostingView;
@synthesize buttonsView = _buttonsView;
@synthesize notesButton = _notesButton;
@synthesize detailsButton = _detailsButton;
@synthesize masterPopoverController;
@synthesize dm;

#define kNumberOfPages 2
#define kCurrentPlot @"SelectedCollectorPlot" 
#define kPriorPlot @"ProiorYearPlot" 
#define kAllCollectorsPlot @"AllCollectorsPlot"

#pragma mark - Managing the detail item

- (void) setDetailsButton:(UIButton *)detailsButton
{
    _detailsButton = detailsButton;
    CAGradientLayer *gradientLayer = [ColorUtility buttonGradientLayer];
    
    gradientLayer.frame = _detailsButton.layer.bounds;
    [_detailsButton.layer insertSublayer:gradientLayer atIndex:0];
    _detailsButton.titleLabel.textColor = [UIColor whiteColor];
}

- (void) setNotesButton:(UIButton *)notesButton
{
    _notesButton = notesButton;
    CAGradientLayer *gradientLayer = [ColorUtility buttonGradientLayer];
    
    gradientLayer.frame = _notesButton.layer.bounds;
    [_notesButton.layer insertSublayer:gradientLayer atIndex:0];
    _notesButton.titleLabel.textColor = [UIColor whiteColor];
    
}

- (void) setButtonsView:(UIView *)buttonsView
{
    _buttonsView = buttonsView;
    
    CAGradientLayer *gradientLayer = [ColorUtility toolBarGradientLayer];
    
    gradientLayer.frame = _buttonsView.layer.bounds;
    [_buttonsView.layer insertSublayer:gradientLayer atIndex:0];
}

- (void)setPriorButton:(UIButton *)priorButton
{
        
    CAGradientLayer *gradientLayer = [ColorUtility buttonGradientLayer];
    
    //[priorButton.layer addSublayer:gradientLayer];
    gradientLayer.frame = priorButton.layer.bounds;
    [priorButton.layer insertSublayer:gradientLayer atIndex:0];
    priorButton.titleLabel.textColor = [UIColor whiteColor];
    
    _priorButton = priorButton;

}

- (void)setAllCollectorsButton:(UIButton *)allCollectorsButton
{
    CAGradientLayer *gradientLayer = [ColorUtility buttonGradientLayer];
    
    //[priorButton.layer addSublayer:gradientLayer];
    gradientLayer.frame = allCollectorsButton.layer.bounds;
    [allCollectorsButton.layer insertSublayer:gradientLayer atIndex:0];
    allCollectorsButton.titleLabel.textColor = [UIColor whiteColor];
    
    _allCollectorsButton = allCollectorsButton;
}

- (void)setDetailItem:(id)newDetailItem
{
    if (_detailItem != newDetailItem) {
        _detailItem = newDetailItem;
        
        // Update the view.
        [self configureView];
    }
    
    if (self.masterPopoverController != nil) {
        [self.masterPopoverController dismissPopoverAnimated:YES];
    }        
}

- (IBAction)allCollectorsButtonPressed:(UIButton *)sender {
          
    if (allCollectorsPlotAdded){
        [linePlot removePlot:@"AllCollectorsPlot"];
        allCollectorsPlotAdded = NO;
        self.allCollectorsButton.titleLabel.textColor = [UIColor whiteColor];
    }
    else{
        [linePlot addPlot:@"AllCollectorsPlot"];
        allCollectorsPlotAdded = YES;
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            self.allCollectorsButton.highlighted = YES;
            self.allCollectorsButton.titleLabel.textColor = [UIColor blueColor];
        }];
           
    }

}

- (IBAction)priorPeriodButtonPressed:(id)sender {
    
    if (priorPlotAdded){
        [linePlot removePlot:kPriorPlot];
        priorPlotAdded = NO;
        self.priorButton.titleLabel.textColor = [UIColor whiteColor];
    }
    else{
        [linePlot addPlot:kPriorPlot];
        priorPlotAdded = YES;
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            self.priorButton.highlighted = YES;
            self.priorButton.titleLabel.textColor = [UIColor blueColor];
        }];
        
    }
}

- (void)configureView
{
    // Update the user interface for the detail item.
    
    /* calvin: I removed this label.
     if (self.detailItem) {
     self.detailDescriptionLabel.text = [self.detailItem description];
     }
     */
}


#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)sender {
    // Update the page when more than 50% of the previous/next page is visible
    CGFloat pageWidth = self.scrollView.frame.size.width;
    int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    self.pageControl.currentPage = page;
   
}


- (IBAction)changePage:(UIPageControl *)sender{
    // update the scroll view to the appropriate page
    
    
    CGRect frame;
    frame.origin.x = self.scrollView.frame.size.width * self.pageControl.currentPage;
    frame.origin.y = 0;
    frame.size = self.scrollView.frame.size;
    [self.scrollView scrollRectToVisible:frame animated:YES];
}



- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    pageControlBeingUsed = NO;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    pageControlBeingUsed = NO;
}




#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"CEIToCollectorSegue"])
    {
        CustomerDetailTableViewController *collectorVC = (CustomerDetailTableViewController *)segue.destinationViewController;
        collectorVC.objectType = @"Collector";
    } 
}


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * kNumberOfPages, self.scrollView.frame.size.height);
    
    self.scrollView.delegate = self;
    self.view.backgroundColor = [UIColor colorWithWhite:0.7f alpha:1.0f];
    
    
    //initialze the data model
    dm = [[CEIDataModel alloc] init];
    dmCopy = [[CEIDataModel alloc] init];
   
    
    
    //draw the line plots
    EskPlotTheme *defaultTheme = [[EskPlotTheme alloc] init];
    linePlot = [[CEILinePlot alloc] initWithOneCollectorData:dm.dailyCEI allCollectorsData:dm.allCEI];
    [linePlot renderInLayer:_lineHostingView withTheme:defaultTheme];
    
    //draw the slider plot
    sliderPlot = [[CEISliderPlot alloc] initWithOneCollectorData:dmCopy.dailyCEI monthlyData:dm.monthlyCEIKeys];
    sliderPlot.delegate = self;
    [sliderPlot renderInLayer:_sliderHostingView withTheme:defaultTheme];

    
    allCollectorsPlotAdded = NO;
    priorPlotAdded = NO;
    
    
    //prepare the country bar plots
    NSArray *country = [NSArray arrayWithObjects:@"",@"Brazil",@"China",@"India",@"Russia", nil];
    NSMutableDictionary *countryCEI = [[NSMutableDictionary alloc] init]; 
    NSMutableDictionary *allCEI = [[NSMutableDictionary alloc] init]; 
    /*for (int d=0; d<[country count]; d++){
        
        //for current plot and prior year
        CEIData *data = [[CEIData alloc] init];
        data.ceiDate = [NSDate date];
        data.ceiPercent = [NSNumber numberWithFloat:(80.0 - d*2)];
        data.priorYearPercent = [NSNumber numberWithFloat:(70.0 - d*2)];
        data.timeIntervalSinceStart = 0;
        data.timeIntervalSinceToday = 0;
        [countryCEI setObject:data forKey:[country objectAtIndex:d]];
        
        
        //for all collectors plot
        CEIData *dataAll = [[CEIData alloc] init]; 
        dataAll.ceiDate = [NSDate date];
        dataAll.ceiPercent = [NSNumber numberWithFloat:(60.0 - d*2)];
        dataAll.priorYearPercent = [NSNumber numberWithFloat:(50.0 - d*2)];
        dataAll.timeIntervalSinceStart = 0;
        dataAll.timeIntervalSinceToday = 0;
        [allCEI setObject:dataAll forKey:[country objectAtIndex:d]];
    }*/
    
    CEIData *data = [[CEIData alloc] init];
    data.ceiDate = [NSDate date];
    data.ceiPercent = [NSNumber numberWithFloat:(0.0)];
    data.priorYearPercent = [NSNumber numberWithFloat:(0.0)];
    data.timeIntervalSinceStart = 0;
    data.timeIntervalSinceToday = 0;
    [countryCEI setObject:data forKey:[country objectAtIndex:0]];
    CEIData *dataAll = [[CEIData alloc] init]; 
    dataAll.ceiDate = [NSDate date];
    dataAll.ceiPercent = [NSNumber numberWithFloat:(0.0)];
    dataAll.priorYearPercent = [NSNumber numberWithFloat:(0.0)];
    dataAll.timeIntervalSinceStart = 0;
    dataAll.timeIntervalSinceToday = 0;
    [allCEI setObject:dataAll forKey:[country objectAtIndex:1]];
    
    //data for Brazil
    CEIData *dataBr = [[CEIData alloc] init];
    dataBr.ceiDate = [NSDate date];
    dataBr.ceiPercent = [NSNumber numberWithFloat:(80.0)];
    dataBr.priorYearPercent = [NSNumber numberWithFloat:(78.0)];
    dataBr.timeIntervalSinceStart = 0;
    dataBr.timeIntervalSinceToday = 0;
    [countryCEI setObject:dataBr forKey:[country objectAtIndex:1]];
    CEIData *dataBrAll = [[CEIData alloc] init]; 
    dataBrAll.ceiDate = [NSDate date];
    dataBrAll.ceiPercent = [NSNumber numberWithFloat:(70.0)];
    dataBrAll.priorYearPercent = [NSNumber numberWithFloat:(68.0)];
    dataBrAll.timeIntervalSinceStart = 0;
    dataBrAll.timeIntervalSinceToday = 0;
    [allCEI setObject:dataBrAll forKey:[country objectAtIndex:1]];
    
    //data for China
    CEIData *dataCh = [[CEIData alloc] init];
    dataCh.ceiDate = [NSDate date];
    dataCh.ceiPercent = [NSNumber numberWithFloat:(63.0)];
    dataCh.priorYearPercent = [NSNumber numberWithFloat:(68.0)];
    dataCh.timeIntervalSinceStart = 0;
    dataCh.timeIntervalSinceToday = 0;
    [countryCEI setObject:dataCh forKey:[country objectAtIndex:2]];
    CEIData *dataChAll = [[CEIData alloc] init]; 
    dataChAll.ceiDate = [NSDate date];
    dataChAll.ceiPercent = [NSNumber numberWithFloat:(70.0)];
    dataChAll.priorYearPercent = [NSNumber numberWithFloat:(68.0)];
    dataChAll.timeIntervalSinceStart = 0;
    dataChAll.timeIntervalSinceToday = 0;
    [allCEI setObject:dataChAll forKey:[country objectAtIndex:2]];
    
    //data for India
    CEIData *dataIn = [[CEIData alloc] init];
    dataIn.ceiDate = [NSDate date];
    dataIn.ceiPercent = [NSNumber numberWithFloat:(92.0)];
    dataIn.priorYearPercent = [NSNumber numberWithFloat:(83.0)];
    dataIn.timeIntervalSinceStart = 0;
    dataIn.timeIntervalSinceToday = 0;
    [countryCEI setObject:dataIn forKey:[country objectAtIndex:3]];
    CEIData *dataInAll = [[CEIData alloc] init]; 
    dataInAll.ceiDate = [NSDate date];
    dataInAll.ceiPercent = [NSNumber numberWithFloat:(70.0)];
    dataInAll.priorYearPercent = [NSNumber numberWithFloat:(68.0)];
    dataInAll.timeIntervalSinceStart = 0;
    dataInAll.timeIntervalSinceToday = 0;
    [allCEI setObject:dataInAll forKey:[country objectAtIndex:3]];
    
    //data for Russia
    CEIData *dataRu = [[CEIData alloc] init];
    dataRu.ceiDate = [NSDate date];
    dataRu.ceiPercent = [NSNumber numberWithFloat:(68.0)];
    dataRu.priorYearPercent = [NSNumber numberWithFloat:(74.0)];
    dataRu.timeIntervalSinceStart = 0;
    dataRu.timeIntervalSinceToday = 0;
    [countryCEI setObject:dataRu forKey:[country objectAtIndex:4]];
    CEIData *dataRuAll = [[CEIData alloc] init]; 
    dataRuAll.ceiDate = [NSDate date];
    dataRuAll.ceiPercent = [NSNumber numberWithFloat:(70.0)];
    dataRuAll.priorYearPercent = [NSNumber numberWithFloat:(68.0)];
    dataRuAll.timeIntervalSinceStart = 0;
    dataRuAll.timeIntervalSinceToday = 0;
    [allCEI setObject:dataRuAll forKey:[country objectAtIndex:4]];

    
    
    barPlot = [[CEIBarPlot alloc] initWithCountryNames:country andCurrentData:countryCEI andAllCollectorsData:allCEI];        
    
    [barPlot renderInLayer:_barHostingView withTheme:defaultTheme];
    self.view.backgroundColor = [UIColor colorWithWhite:0.7f alpha:1.0f];

    
}


- (void)viewDidUnload
{
    [self setPageControl:nil];
    [self setScrollView:nil];
    [self setLineHostingView:nil];
    [self setSliderHostingView:nil];
    [self setPriorButton:nil];
    [self setAllCollectorsButton:nil];
    [self setBarHostingView:nil];
    [self setButtonsView:nil];
    [self setNotesButton:nil];
    [self setDetailsButton:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
	return YES;
}

#pragma mark - Split view

- (void)splitViewController:(UISplitViewController *)splitController willHideViewController:(UIViewController *)viewController withBarButtonItem:(UIBarButtonItem *)barButtonItem forPopoverController:(UIPopoverController *)popoverController
{
    barButtonItem.title = NSLocalizedString(@"Master", @"Master");
    [self.navigationItem setLeftBarButtonItem:barButtonItem animated:YES];
    self.masterPopoverController = popoverController;
}

- (void)splitViewController:(UISplitViewController *)splitController willShowViewController:(UIViewController *)viewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem
{
    // Called when the view is shown again in the split view, invalidating the button and popover controller.
    [self.navigationItem setLeftBarButtonItem:nil animated:YES];
    self.masterPopoverController = nil;
}

#pragma mark - CEISliderPlot Delegate

- (void)sliderPlot:(CEISliderPlot *)plot fromDate:(NSString *)fromDateString toDate:(NSString *)toDateString{
    
    [linePlot respondToRangeChangeFromDate:fromDateString toDate:toDateString];

}
@end
